from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .models import ChatRoom,RoomMessage
from django.contrib import messages
from channels.db import database_sync_to_async
from .forms import CreateRoomForm
from django.contrib.auth import get_user_model
from django.http import JsonResponse
from django.db.models import Count
User = get_user_model()
# Create your views here.
@login_required
def room_list(req):
    all_rooms = ChatRoom.objects.annotate(member_count=Count('members',distinct=True)).values_list('name','id','member_count','create_time').order_by('-create_time')
    joined_rooms_qs = ChatRoom.objects.filter(members=req.user)
    joined_rooms = [
        (room.name, room.id, room.members.count(), room.create_time)
        for room in joined_rooms_qs
    ]
    # 断开连接不等于退出聊天室，点退出聊天室才是退出，返回是返回
    created_rooms = req.user.create_rooms.annotate(member_count=Count('members',distinct=True)).values_list('name','id','member_count','create_time').order_by('-create_time')
    return render(req,'Chat/room_list.html',{
        'all_rooms':all_rooms,
        'joined_rooms':joined_rooms,
        'created_rooms':created_rooms
    })

@database_sync_to_async
def user_can_join(self):
    return self.room.user_can_join(self.user)
@login_required
def chat_room(req,room_id):
    room = ChatRoom.objects.filter(id=room_id,is_activate=True).first()
    if not room:
        messages.error(req,'房间不存在，请刷新页面')  # 会将message写入session或cookie
        return redirect('Chat:room_list')
    if not room.user_can_join(req.user): # 自定义的模型只影响数据库和代码里用户类的定义
        messages.error(req,'您没有权限加入此聊天室')
        return redirect('Chat:room_list')
    room.add_member(req.user)
    msgs = room.room_messages.order_by('timestamp').values_list('user__username','content','timestamp','is_deepseek')
    room_members = room.members.values_list('id','username').order_by('username')
    # 把相关的user也查出来 省的前端调用user.name会再查询一次
    return render(req,'Chat/chat_room.html',{
        'room_name':room.name,
        'room_id':room_id,
        'room_members':list(room_members),
        'messages':list(msgs)
    })

@login_required
def create_room(req):
    if req.method=='POST':
        form = CreateRoomForm(req.POST)
        if form.is_valid():
            room = form.save(commit=False)
            # form.save()会返回一个模型实例，也就是form保存的
            # 用commit=False就表示先不保存到数据库
            room.creator = req.user
            room.save()
            # 这里一定要先保存，才会有id，不然下面的添加用户会报错
            # ManyToMany 的操作（room.add_member(req.user)）都需要 实例在数据库里有 id
            room.add_member(req.user)
            messages.success(req,f'聊天室 “{room.name}”创建成功！')
            room.save()
            return redirect('Chat:chat_room',room_id=room.id)
            # 这种name方法在redirect和reverse中用 解析url
            # 后面的room_name是传给url的参数 （url<str:room_name>，name='chat_room'）
            # 在模板中这样用<a href="{% url 'chat:chat_room' room_name=room.name %}">进入聊天室</a>
        else:
            messages.success(req, f'房间名有误或重复，请重试！')
            return redirect('Chat:create_room')


    else:
        form = CreateRoomForm()
        return render(req,'Chat/create_room.html',{'form':form})


@login_required
def delete_room(req,room_id):
    room = ChatRoom.objects.filter(id=room_id).first()
    if req.method == 'POST':
        if room:
            room.delete()
            messages.success(req,f'房间{room.name}删除成功')
            return redirect('Chat:room_list')
        else:
            messages.error(req,'房间不存在，请刷新页面')
            return redirect('Chat:room_list')
    return render(req,'Chat/delete_room.html',{'room':room})

@login_required
def manage_room(req,room_id):
    room = ChatRoom.objects.filter(id=room_id).first()
    if room:
        members = room.members.exclude(id=room.creator_id).values_list('username','id').order_by('username')
        # 如果只需id，就不用.id，这会额外查询一次数据库，用_id会更快
        if req.method =='POST':
            if room.creator.id != req.user.id:
                messages.error(req,'您没有权限管理此房间')
                return redirect('Chat:room_list')
            # user_id = req.POST.get('user_id')
            # room_name = req.POST.get('room_name')
            # room_description = req.POST.get('room_name')
            form = CreateRoomForm(data=req.POST,instance=room)
            if form.is_valid():
                form.save()
                return redirect('Chat:room_list')
            else:
                messages.error(req,'房间内容不符合格式，请重试')
                return redirect('Chat:manage_room')
        else:
            form = CreateRoomForm()
            return render(req,'Chat/manage_room.html',{'room_name':room.name,'room_id':room.id,'form':form,'members':list(members)})
    else:
        messages.error(req,'房间不存在！')
        return redirect('Chat:room_list')


@login_required
def remove_block_user(request,user_id, room_id):
    if request.method != 'POST':
        return JsonResponse({'error': '只支持POST'}, status=405)
    room = ChatRoom.objects.filter(id=room_id).first()
    if room.creator != request.user:
        return JsonResponse({'error': '无权限'}, status=403)
    user = User.objects.filter(id=user_id).first()
    if not user or not room.members.filter(id=user_id).exists():
        return JsonResponse({'error': '用户不存在或不在房间'}, status=400)
    room.remove_member(user)
    room.add_block(user)
    # JsonResponse适合fetch异步调用 会返回Json格式
    return JsonResponse({'success': True, 'message': f'已移除并拉黑用户{user.username}'})


@login_required
def leave_room(request, room_id):
    room = ChatRoom.objects.filter(id=room_id).first()
    if room.remove_member(request.user):
        messages.info(request, f'您已离开聊天室: {room.name}')
    else:
        messages.error(request, f'离开聊天室: {room.name}失败')
    return redirect('Chat:room_list')








